<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>App映射管理</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd"
        >
          新增
        </el-button>
      </div>

      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
      >
        <el-table-column label="App名称" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.appName }}</span>
          </template>
        </el-table-column>

        <el-table-column label="真实 API Key" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ maskApiKey(scope.row.realApiKey) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="描述" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.description || '-' }}</span>
          </template>
        </el-table-column>

        <el-table-column label="状态" align="center" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" align="center" width="180">
          <template slot-scope="scope">
            <span>{{ formatTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="更新时间" align="center" width="180">
          <template slot-scope="scope">
            <span>{{ formatTime(scope.row.updateTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="mini"
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="handleStatusChange(scope.row)"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 新增/编辑对话框 -->
      <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="600px"
        @close="handleDialogClose"
      >
        <el-form
          ref="dataForm"
          :model="temp"
          :rules="rules"
          label-position="left"
          label-width="120px"
          style="width: 500px; margin-left: 20px;"
        >
          <el-form-item label="App名称" prop="appName">
            <el-input
              v-model="temp.appName"
              placeholder="请输入App名称"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="真实 API Key" prop="realApiKey">
            <el-input
              v-model="temp.realApiKey"
              type="textarea"
              :rows="3"
              placeholder="请输入真实的API Key"
            />
          </el-form-item>

          <el-form-item label="描述">
            <el-input
              v-model="temp.description"
              type="textarea"
              :rows="3"
              placeholder="请输入描述信息"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="状态">
            <el-radio-group v-model="temp.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  getAppMappingList,
  getAppMappingById,
  saveAppMapping,
  updateAppMapping,
  deleteAppMapping,
  updateAppMappingStatus
} from '@/api/apikey/mapping'

export default {
  name: 'ApiKeyManage',
  data() {
    return {
      list: [],
      listLoading: true,
      dialogVisible: false,
      dialogTitle: '新增',
      temp: {
        appName: '',
        realApiKey: '',
        description: '',
        status: 1
      },
      rules: {
        appName: [
          { required: true, message: 'App名称不能为空', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        realApiKey: [
          { required: true, message: '真实API Key不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      getAppMappingList().then(response => {
        // 确保 list 始终是数组
        if (Array.isArray(response.data)) {
          this.list = response.data
        } else if (response.data && Array.isArray(response.data.list)) {
          this.list = response.data.list
        } else if (response.data && Array.isArray(response.data.data)) {
          this.list = response.data.data
        } else {
          this.list = []
        }
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.listLoading = false
      })
    },
    handleAdd() {
      this.dialogTitle = '新增'
      this.temp = {
        appName: '',
        realApiKey: '',
        description: '',
        status: 1
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleEdit(row) {
      this.dialogTitle = '编辑'
      this.temp = Object.assign({}, row)
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.dialogTitle === '编辑') {
            // 更新
            updateAppMapping(this.temp).then(() => {
              this.$message.success('更新成功')
              this.dialogVisible = false
              this.fetchData()
            }).catch(() => {
              this.$message.error('更新失败')
            })
          } else {
            // 新增 - 检查是否已存在（通过realApiKey判断）
            const existing = this.list.find(item => item.realApiKey === this.temp.realApiKey)
            if (existing) {
              this.$message.warning('该API Key已存在')
              return
            }
            // 新增
            saveAppMapping(this.temp).then(() => {
              this.$message.success('新增成功')
              this.dialogVisible = false
              this.fetchData()
            }).catch(() => {
              this.$message.error('新增失败')
            })
          }
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确定要删除该App映射吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteAppMapping(row.realApiKey).then(() => {
          this.$message.success('删除成功')
          this.fetchData()
        }).catch(() => {
          this.$message.error('删除失败')
        })
      })
    },
    handleStatusChange(row) {
      const newStatus = row.status === 1 ? 0 : 1
      const statusText = newStatus === 1 ? '启用' : '禁用'
      this.$confirm(`确定要${statusText}该App映射吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateAppMappingStatus(row.realApiKey, newStatus).then(() => {
          this.$message.success(`${statusText}成功`)
          this.fetchData()
        }).catch(() => {
          this.$message.error(`${statusText}失败`)
        })
      })
    },
    handleDialogClose() {
      this.$refs['dataForm'].clearValidate()
    },
    maskApiKey(apiKey) {
      if (!apiKey || apiKey.length < 8) {
        return apiKey
      }
      const start = apiKey.substring(0, 4)
      const end = apiKey.substring(apiKey.length - 4)
      return `${start}${'*'.repeat(Math.max(apiKey.length - 8, 0))}${end}`
    },
    formatTime(time) {
      if (!time) return '-'
      const date = new Date(time)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.clearfix::after {
  content: "";
  display: table;
  clear: both;
}
</style>

